<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="关联鱼塘" prop="fishPondId">
                <el-select v-model="ruleForm.fishPondId" filterable clearable class="w100p" @change="getTableDataList">
                    <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                        :value="item.fishPondId" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="addEditFlag == 'add'" label="选择数据项" prop="dataItemId">
                <el-select class="w100p" filterable clearable v-model="ruleForm.dataItemId" placeholder="请选择"
                    @change="handleChangeItem">
                    <el-option v-for="(item, index) in dataItemList" :label="item.dataItemName" :value="item.dataItemId"
                        :key="index + 'dataItem'" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="addEditFlag == 'edit'" label="选择数据项">
                <el-input disabled v-model="ruleForm.dataItemName" clearable class="w100p"></el-input>
            </el-form-item>
            <el-form-item label="采集值" prop="value">
                <el-input v-model="ruleForm.value" clearable placeholder="请输入数量" type="number" class="w100p">
                    <template slot="append">{{ ruleForm.unitName }}</template>
                </el-input>
            </el-form-item>
            <el-form-item label="采集人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="采集时间" prop="accumulationTime">
                <el-date-picker v-model="ruleForm.accumulationTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                    placeholder="选择日期" :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm"
                @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" v-show="!ruleForm.inputPondId" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import waterQualityInformationInput from '@/api/disease-prevention-and-control/water-quality-information-input.js';
import environmentalDataMonitoringApi from "@/api/iot-monitoring/environmental-data-monitoring";
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        fishVarietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            dataItemList: [],
            rules: {
                fishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                value: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                accumulationTime: [
                    { required: true, message: '请选择采集时间', trigger: 'change' }
                ],
                dataItemId: [
                    { required: true, message: '请选择采集数据项', trigger: 'change' }
                ],
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = waterQualityInformationInput.add
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = waterQualityInformationInput.edit
                this.addEditName = '编辑'
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
                this.getTableDataList(data.fishPondId)
            })
        },
        // 获取数据类型
        getTableDataList(e) {
            this.dataItemList = []
            if (e) {
                environmentalDataMonitoringApi.queryNewByFishPondId({ fishPondId: e }).then(res => {
                    let dataList = res.data || [];
                    let itemList = dataList.filter(item => {
                        return item.dataType && item.dataType.mainingControlType == "COLLECTION"
                    })
                    if (res.success && itemList.length > 0) {
                        this.dataItemList = itemList;
                    } else {
                        this.dataItemList = []
                        this.$set(this.ruleForm, 'dataItemId', '')
                    }
                });
            } else {
                this.$set(this.ruleForm, 'dataItemId', '')
            }
        },
        //获取选中的数据项
        handleChangeItem(id) {
            let rut = this.dataItemList.find(item => { return item.dataItemId == id });
            let unitName = rut.dataType?.unit || ''
            let firstValue = rut.dataCollectNew?.firstValue||''
            this.$set(this.ruleForm, 'dataItemName', rut.dataItemName)
            this.$set(this.ruleForm, 'value', firstValue)
            this.$set(this.ruleForm, 'unitName', unitName)
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                accumulationTime: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
            }
            this.$set(this, 'ruleForm', params);
        },
        //获取称重人姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        //提交数据时删除保存的记录
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped></style>